<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request';

// 自定义手机号校验函数
const checkPhone = (rule, value, callback) => {
    if (!/^1[3|4|5|7|8][0 - 9]{9}$/.test(value)) {
        return callback(new Error('请检查手机号是否正确'));
    }
    return callback();
};

// 自定义身份证号校验函数
const checkCardNumber = (rule, value, callback) => {
    if (!/^([1 - 6][1 - 9]|50)\d{4}(18|19|20)\d{2}((0[1 - 9])|10|11|12)(([0 - 2][1 - 9])|10|20|30|31)\d{3}[0 - 9Xx]$/.test(value)) {
        return callback(new Error('请输入正确格式的身份证号'));
    }
    return callback();
};

// 响应式数据
const loading = ref(true);
const ruleForm = ref({});
const dialogVisible = ref(false);
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const vis = ref(false);
const detail = ref({});
const loginUser = ref({});
const formDisabled = ref(false);

const rules = {
    phone: [
        { required: true, message: '请输入电话号', trigger: 'blur' },
        { validator: checkPhone, trigger: 'blur' }
    ],
    cardNumber: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { validator: checkCardNumber, trigger: 'blur' }
    ]
};

// 组件挂载后执行的操作
onMounted(() => {
    const userStr = sessionStorage.getItem('user') || '{}';
    loginUser.value = JSON.parse(userStr);
    console.log('当前登陆者信息：', loginUser.value);
    load();
});

// 查看详情方法
const details = (row) => {
    ruleForm.value = row;
    dialogVisible.value = true;
    formDisabled.value = true;
};

// 关闭对话框并重新加载数据方法
const dialogVisibleClose = () => {
    dialogVisible.value = false;
    load();
};

// 加载数据方法
const load = () => {
    loading.value = true;
    const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        search: search.value
    };
    if (loginUser.value.roles[0] === 2) {
        params.userId = loginUser.value.id;
    }
    console.log('params：：', params);
    request.get('/checkFiles', { params }).then((res) => {
        loading.value = false;
        tableData.value = res.data.records;
        total.value = res.data.total;
    });
};

// 添加方法
const add = () => {
    dialogVisible.value = true;
    formDisabled.value = false;
    ruleForm.value = {};
    ruleForm.value.userName = loginUser.value.nickName;
    ruleForm.value.userId = loginUser.value.id;
    ruleForm.value.sex = loginUser.value.sex;
    ruleForm.value.age = loginUser.value.age;
};

// 保存方法
const save = (formName) => {
    const form = getCurrentInstance().proxy.$refs[formName];
    form.validate((valid) => {
        if (valid) {
            if (ruleForm.value.id) {
                ruleForm.value.address = loginUser.value.address;
                console.log('修改健康档案', ruleForm.value);
                request.put('/checkFiles', ruleForm.value).then((res) => {
                    if (res.code === '0') {
                        app.config.globalProperties.$message({
                            type:'success',
                            message: '更新成功'
                        });
                    } else {
                        app.config.globalProperties.$message({
                            type: 'error',
                            message: res.msg
                        });
                    }
                    load();
                    dialogVisible.value = false;
                });
            } else {
                const userStr = sessionStorage.getItem('user') || '{}';
                const user = JSON.parse(userStr);
                ruleForm.value.createPeople = user.nickName;
                ruleForm.value.address = loginUser.value.address;
                console.log('你要新增健康档案');
                console.log('this.ruleForm::', ruleForm.value);
                request.post('/checkFiles', ruleForm.value).then((res) => {
                    if (res.code === '0') {
                        app.config.globalProperties.$message({
                            type:'success',
                            message: '新增成功'
                        });
                    } else {
                        app.config.globalProperties.$message({
                            type: 'error',
                            message: res.msg
                        });
                    }
                    load();
                    dialogVisible.value = false;
                });
            }
        } else {
            console.log('error submit!!');
            return false;
        }
    });
};

// 编辑方法
const handleEdit = (row) => {
    ruleForm.value = JSON.parse(JSON.stringify(row));
    dialogVisible.value = true;
    formDisabled.value = false;
};

// 删除方法
const handleDelete = (id) => {
    request.delete(`/checkItems/${id}`).then((res) => {
        if (res.code === '0') {
            app.config.globalProperties.$message({
                type:'success',
                message: '删除成功'
            });
        } else {
            app.config.globalProperties.$message({
                type: 'error',
                message: res.msg
            });
        }
        load();
    });
};

// 改变每页个数方法
const handleSizeChange = (newPageSize) => {
    pageSize.value = newPageSize;
    load();
};

// 改变当前页码方法
const handleCurrentChange = (newPageNum) => {
    currentPage.value = newPageNum;
    load();
};
</script>

<template>
  <div style="padding: 10px">
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入姓名进行查询" style="width: 20%" clearable></el-input>
      <el-button style="margin-left: 5px" @click="load">查询</el-button>
      <el-button type="primary" @click="add" v-if="loginUser.roles[0] == 2">新增</el-button>
    </div>
    <el-table v-loading="loading" :data="tableData" border stripe style="width: 100%">

      <template #empty>
        <el-empty description="您还没有建立健康档案呦~~~" />
      </template>

      <el-table-column type="index" label="序号" sortable align="center">
      </el-table-column>
      <el-table-column prop="userName" label="姓名" align="center">
      </el-table-column>
      <el-table-column prop="age" label="年龄" align="center">
      </el-table-column>
      <el-table-column prop="sex" label="性别" align="center">
      </el-table-column>
      <el-table-column prop="cardNumber" label="身份证号" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="details(scope.row)">查看健康档案</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)"
            v-if="loginUser.roles[0] == 2">编辑</el-button>
          <!-- <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
  </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="健康档案信息" v-model="dialogVisible" style="width: 50%; margin: 0 auto 50px;">
      <el-form :disabled="formDisabled" :model="ruleForm" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="姓名">
          <el-input v-model="ruleForm.userName" style="width: 15%;"></el-input>
          <label style="margin-left: 3%;">年龄：</label>
          <el-input v-model="ruleForm.age" style="width: 6%;"></el-input>&nbsp;&nbsp;<span>岁</span>
          <label style="margin-left: 3%;">性别：</label>
          <el-radio style="width: 7%;" v-model="ruleForm.sex" label="男">男</el-radio>
          <el-radio style="width: 7%;" v-model="ruleForm.sex" label="女">女</el-radio>
        </el-form-item>

        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="ruleForm.phone" style="width: 25%;"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="cardNumber">
          <el-input v-model="ruleForm.cardNumber" style="width: 45%;"></el-input>
        </el-form-item>

        <el-form-item label="血型">
          <el-select v-model="ruleForm.bloodType" style="width: 18%;" placeholder="请选择">
            <el-option label="A型" value="A" />
            <el-option label="B型" value="B" />
            <el-option label="O型" value="O" />
            <el-option label="AB型" value="AB" />
            <el-option label="RH型" value="RH" />
          </el-select>
        </el-form-item>

        <el-form-item label="身高">
          <el-input v-model="ruleForm.height" style="width: 10%;"></el-input>&nbsp;&nbsp;<span>cm</span>
          <label style="margin-left: 3%;">体重：</label>
          <el-input v-model="ruleForm.weight" style="width: 10%;"></el-input>&nbsp;&nbsp;<span>kg</span>
        </el-form-item>

        <el-form-item label="既往病史">
          <el-input type="textarea" :rows="3" placeholder="请输入既往病史" v-model="ruleForm.medicalHistory"></el-input>
        </el-form-item>

        <el-form-item label="补充说明">
          <el-input type="textarea" :rows="2" placeholder="补充信息" v-model="ruleForm.remark"></el-input>
        </el-form-item>


      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleClose">取 消</el-button>
          <el-button v-show="!formDisabled" type="primary" @click="save('formRef')">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="详情" v-model="vis" width="50%">
      <el-card>
        <div v-html="detail.content" style="min-height: 100px"></div>
      </el-card>
    </el-dialog>

  </div>
</template>
